package com.ultrawise.survey.core;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UploadAction
{
	@RequestMapping(value = "/upload.htm")
	public String upload(@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request, ModelMap model)
	{
		String resultURL = request.getParameter("resultURL");
		String path = request.getSession().getServletContext().getRealPath("/") + "\\" + "uploadfile\\";
		// String path = PropertiesHandler.getMessage("upload.file.realpath");

		String fileName = file.getOriginalFilename();
		File targetFile = new File(path, fileName);
		String fileSize = "";
		if (!targetFile.exists())
		{
			targetFile.mkdirs();
		}

		// 保存
		try
		{
			file.transferTo(targetFile);
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		List fileList = getUploadFile(path);
		model.put("fileList", fileList);
		return resultURL;
	}

	@RequestMapping(value = "/getuploadfile.htm")
	public static List getUploadFile(String fileurl)
	{

		// String fileurl = PropertiesHandler.getMessage("upload.file.realpath");
		File file = new File(fileurl);
		File[] tempList = file.listFiles();
		List<Map> list = new ArrayList();
		for (int i = 0; i < tempList.length; i++)
		{
			Map<String, String> map = new HashMap();
			if (tempList[i].isFile())
			{
				String fileSize = (double) (tempList[i].length() / 1024) + "kb";
				String fileName = tempList[i].getName();
				map.put("filename", fileName);
				map.put("filesize", fileSize);
			}
			list.add(map);
		}
		return list;
	}

	@RequestMapping("/download.htm")
	public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		String fileName = new String(request.getParameter("fileName").getBytes("ISO-8859-1"), "utf-8");
		// String fileName = request.getParameter("fileName");
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;

		String ctxPath = request.getSession().getServletContext().getRealPath("/") + "\\" + "uploadfile\\";
		String downLoadPath = ctxPath + fileName;
		System.out.println(downLoadPath);
		try
		{
			long fileLength = new File(downLoadPath).length();
			response.setContentType("application/x-msdownload;");
			fileName = URLEncoder.encode(fileName, "UTF-8");
			/*
			 * see http://support.microsoft.com/default.aspx?kbid=816868
			 */
			if (fileName.length() > 150)
			{
				String guessCharset = request.getLocale().getLanguage(); /* 根据request的locale 得出可能的编码，中文操作系统通常是gb2312 */
				fileName = new String(fileName.getBytes(guessCharset), "ISO8859-1");
			}

			response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
			{
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		} finally
		{
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
		return null;
	}

}
